<template>
  <div class="login-container">
    <h1 class="main-title">健康生活助手</h1>
    <!-- 直接放置卡片 -->
    <el-card class="box-card">
      <h2>欢迎回来！</h2>
      <el-form
          :model="ruleForm"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-position="left"
          label-width="120px"
          class="login-from"
      >
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email" prefix-icon="el-icon-message"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
              type="password"
              v-model="ruleForm.password"
              autocomplete="off"
              prefix-icon="el-icon-lock"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="btnGroup">
        <el-button
            type="primary"
            @click="submitForm('ruleForm')"
            v-loading="loading"
            class="login-button"
        >登录</el-button>
        <div class="extra-links">
          <el-button @click="resetForm('ruleForm')" type="text">重置</el-button>
          <router-link to="/register">
            <el-button type="text">立即注册</el-button>
          </router-link>
        </div>
        <!-- 添加忘记密码按钮 -->
        <!-- <router-link to="/forgot-password"> -->
        <!--   <el-button style="margin-left: 10px" type="text">忘记密码</el-button> -->
        <!-- </router-link> -->
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ruleForm: {
        email: "",
        password: "",
      },
      rules: {
        email: [
          { required: true, message: "邮箱不能为空！", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空！", trigger: "blur" },
        ],
      },
      loading: false, // 是否显示加载动画
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true;
          // 发送登录请求
          this.axios({
            url: "/api/user/login",
            method: "post",
            headers: {
              "Content-Type": "application/json",
            },
            withCredentials: true, // 确保发送请求时携带Cookie
            data: {
              email: this.ruleForm.email,
              password: this.ruleForm.password,
            },
          }).then((res) => {
            if (res.data.message === "登录成功") {
              // 从响应中获取userId
              const userId = res.data.userId;
              
              // 存储用户信息到会话存储
              sessionStorage.setItem("userInfo", JSON.stringify({
                id: userId,
                email: this.ruleForm.email
              }));

              
              this.$message({
                message: "登录成功",
                type: "success",
              });
              
               
              // 检查用户是否已经填写过个人资料
              this.checkUserProfile(userId);
            } else {
              this.loading = false;
              this.$message({
                message: res.data.message || "登录失败",
                type: "warning",
              });
            }
          }).catch((error) => {
            this.loading = false;
            console.error('登录请求失败:', error);
            this.$message({
              message: "登录请求失败，请稍后再试",
              type: "error",
            });
          });
        } else {
          this.loading = false;
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 添加新方法: 检查用户个人资料是否存在
    checkUserProfile(userId) {
      this.axios.get(`/api/userProfile/get`, {
        withCredentials: true, // 确保发送请求时携带Cookie
        headers: {
          'Cache-Control': 'no-cache',
          'Pragma': 'no-cache'
        }
      })
        .then(response => {
          this.loading = false;

          if (response.data && response.data.id) {
            // 用户资料已存在，直接跳转到主页
            this.$router.push('/home');
          } else {
            // 用户资料不存在，跳转到资料填写页面
            this.$router.push('/profile-form');
          }
        })
        .catch(error => {
          this.loading = false;
          console.error('检查用户资料失败:', error);
          
          // 出错时默认跳转到资料填写页面（保守处理）
          this.$router.push('/profile-form');
        });
    }
  },
};
</script>

<style scoped>
.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(120deg, #e3f2fd, #bbdefb, #fce4ec, #f8bbd0);
  position: relative;
}

.main-title {
  margin: 40px 0;
  font-size: 46px;
  font-weight: bold;
  font-family: "STXingkai", "华文行楷", "Microsoft YaHei", "微软雅黑", sans-serif;
  background: linear-gradient(120deg, #1976d2, #2196f3, #ec407a);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  text-shadow: 3px 3px 6px rgba(0, 0, 0, 0.12);
  letter-spacing: 8px;
  position: relative;
  padding: 10px 20px;
}

.main-title::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(120deg, rgba(33, 150, 243, 0.1), rgba(236, 64, 122, 0.1));
  transform: skew(-15deg);
  z-index: -1;
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
}

.main-title::after {
  content: '健康生活助手';
  position: absolute;
  top: 2px;
  left: 2px;
  z-index: -2;
  background: linear-gradient(120deg, #64b5f6, #f48fb1);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  opacity: 0.3;
}

.box-card {
  width: 500px;
  padding: 40px;
  border-radius: 16px;
  box-shadow: 0 8px 25px rgba(33, 150, 243, 0.1);
  background: linear-gradient(to bottom, #ffffff, #f8f8ff);
  border: 1px solid rgba(33, 150, 243, 0.2);
  margin-bottom: 40px;
  position: relative;
  overflow: hidden;
}

.box-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 6px;
  background: linear-gradient(90deg, #2196f3, #ec407a);
}

.box-card h2 {
  background: linear-gradient(120deg, #1976d2, #d81b60);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  text-align: center;
  margin-bottom: 50px;
  font-weight: 600;
  font-size: 36px;
}


.el-form-item {
  margin-bottom: 35px;
}

.login-from >>> .el-form-item__label {
  background: linear-gradient(120deg, #1976d2, #d81b60);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  font-weight: 500;
  font-size: 18px;
  line-height: 45px;
}

.el-input >>> .el-input__inner {
  height: 45px;
  line-height: 45px;
  font-size: 16px;
  border-radius: 10px;
  background-color: #fff;
  border: 1px solid rgba(33, 150, 243, 0.3);
  transition: all 0.3s ease;
  padding-left: 45px;
}

.el-input >>> .el-input__prefix {
  line-height: 45px;
  font-size: 20px;
  color: #90caf9;
  width: 45px;
}

.btnGroup {
  margin-top: 40px;
  display: flex;
  flex-direction: column;
  align-items: stretch;
}

.login-button {
  width: 100%;
  height: 50px;
  font-size: 18px;
  letter-spacing: 2px;
  margin-bottom: 25px;
  background: linear-gradient(90deg, #409EFF, #E040FB) !important;
  border: none !important;
  transition: all 0.3s ease !important;
  border-radius: 25px !important;
}

.login-button:hover {
  opacity: 0.9;
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(33, 150, 243, 0.2);
}

.extra-links {
  display: flex;
  justify-content: space-between;
  width: 100%;
  padding: 0 20px;
}

.extra-links .el-button {
  color: #1976d2 !important;
  transition: all 0.3s ease;
  font-size: 16px;
}

.extra-links .el-button:hover {
  color: #ec407a !important;
  transform: translateY(-1px);
}

.extra-links a {
  text-decoration: none;
}
</style>
